/***************************************************************************
 *
 *   Copyright (C) 2024 by Willem van Straten
 *   Licensed under the Academic Free License version 2.1
 *
 ***************************************************************************/

#include "dsp/DADAHeader.h"
#include "ascii_header.h"
#include "debug.h"

#include <cstring>
#include <cmath>

using namespace std;

const unsigned dsp::DADAHeader::default_header_size = 4096;

void dsp::DADAHeader::set_header(const char* ascii_header)
{
  if (!ascii_header)
    throw Error(InvalidState, "dsp::DADAHeader::set_header", "ascii_header == nullptr");

  unsigned header_size = 0;
  if (ascii_header_get(ascii_header, "HDR_SIZE", "%u", &header_size) < 0)
  {
    header_size = strlen(ascii_header);
    DEBUG("dsp::DADAHeader::set_header required HDR_SIZE=" << header_size);
  }

  resize(header_size);
  strncpy(get_header(), ascii_header, header_size);
}

void dsp::DADAHeader::resize(unsigned requested_header_size)
{
  unsigned header_size = default_header_size;
  while (header_size < requested_header_size)
    header_size *= 2;

  header.resize(header_size);
  memset(get_header(), 0, header_size);

  if (ascii_header_set(get_header(), "HDR_SIZE", "%d", header_size) < 0)
    throw Error (InvalidState, "dsp::DADAHeader::resize", "failed to set HDR_SIZE");
}
